<?php
namespace app\api\controller;
use think\Db;

use \GatewayWorker\Lib\Gateway;
//用户接口
class User extends Base{

    public function __construct(){
        parent::__construct();
    }

    public function login(){
        //var_dump(request()->post());exit;

        $code = input('code');
        $token = $this->token;
        $time = time();
        if(!empty($code)){
            $token_info = \think\Loader::model('DeviceToken')->find($token);
            //var_dump($token_info);exit;
            if(empty($token) && empty($this->user_info)){
                $token_data = $this->get_wx_session_key($code);
                $token = $token_data['token'];
                $res = $this->init_user_info($token_data);
                if(empty($token_info)){
                    \think\Loader::model('DeviceToken')->delete_token($token,$this->user_info['openid']);//
                    $ret_id = db('device_token')->insertGetId($token_data);
                }
				$token_data['user_info'] = !empty($this->user_info) ? serialize($this->user_info):'';//
				\think\Loader::model('DeviceToken')->update_token($token,$token_data);
            }
        }
        $this->json_return(1, "返回数据成功", ['session_key'=>$token,'is_login'=>$this->is_login]);
    }

    //注册用户,返回信息
    public function login_user(){
        $token = $this->token;
        if(empty($this->user_info)){
            $level1=db('grad')->where('sort',1)->find();
            $data = [
                'openid'=>$this->token_data['openid'],//,'onBv60C5VXr6FF0_Cf7A51nrvHTk'
                'avatar'=>input('headimg'),
                'display_name'=>input('nickname'),
                'points'=>config('df_user_points'),//初始100个金币
                'sex'=>input('gender'),
                'country'=>input('country'),
                'province'=>input('province'),
                'city'=>input('city'),
                'grad_id'=>$level1['id'],
                'grad_name'=>$level1['name'],
                'create_time'=>time(),
                'last_login_time'=>time(),
            ];
            $user_id = db('user')->insertGetId($data);
            if($user_id){//更新token表用户信息
                $data['id'] = $user_id;
                $ext_id = db('user_info_extend')->insertGetId(['user_id'=>$user_id]);//扩展表
            }
        }else{//存在着
            $data = $this->user_info;
        }
        //更新
        \think\Loader::model('DeviceToken')->update_token($token,['user_info'=>serialize($data)]);
		
        $this->json_return(1, "返回数据成功", $data);
    }

    //获取用户信息
    public function get_user_info(){
        $token = $this->token;
        $data = $this->user_info;
        if(!empty(input('ver')==config('appver')))$data['check_status'] = 0;//题目工厂开关
        //---我的银行时间start--//
        $bank_ponit_time=Db::name('user_info_extend')->where('user_id', $this->user_info['id'])->value('last_bank_point_time');
        $b_time= time()-$bank_ponit_time;
        $remain = $b_time%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        $last_time =($secs+$mins*60+$hours*60*60)*1000;
        $three_hours=10800000;//3小时
        $flag = date('Y-m-d',$bank_ponit_time)!=date('Y-m-d', time())?true:false;
        if($flag){
            $data['clock']=0;
        }else{
            if($three_hours>$last_time){
                $data['clock']=$three_hours-$last_time;
            }else{
                $data['clock']=0;
            }
        }
        //---我的银行时间end--//
        if(!empty($data)){
            try {
                $base_num = config('df_user_base_num');//默认用户基数
                $data['paiwei_count'] = $base_num + Gateway::getAllClientCount();
            } catch (Exception $e) {
                $data['paiwei_count'] = 0;
            }
        }

        /**是否领取奖励*/
        $start_time = strtotime(date('Y-m-d'));
        $data['is_award']=true;
        $res        = Db::name("reward_log")
                        ->where([
                                    'user_id'     => $this->user_info['id'],
                                    'stage'       => 'login',
                                    'create_time' => [
                                        '>',
                                        $start_time
                                    ]
                                ])
                        ->find();
        if ($res) {
           $data['is_award']=false;
        }
        $next_level_exp = get_user_level($data['exp'],true);
        $data['copy_right'] = config('copy_right'); //2018-04-03 15:43:13
        $data['setting'] = $this->is_setting(true);//用户设置
        $data['exp_scale'] = round($data['exp']/$next_level_exp,2)*100;
        
        $this->json_return(1, "返回数据成功", $data);
    }
	
	//获取微信登信息
	public function get_wx_session_key($code){
        $payment_info = config('wechat.wxapp');//支付配置
        $appid = $payment_info['appid'];
        $appsecret = $payment_info['appsecret'];
        $token_data = [];

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$code.'&grant_type=authorization_code';
        $res = file_get_contents($url);
        $data = json_decode($res,true);
        $token = md5($data['openid'].$data['session_key']);
        $expires_time = time()+86400;//过期时间一天$data['expires_in']
        $token_data = ['token'=>$token,'openid'=>$data['openid'],'session_key'=>$data['session_key'],'expires_in'=>$expires_time,'create_time'=>time()];
        
        return $token_data;
    }
    

    //检查房主是否离开房间
    public function check_sponsor($room_id=0){
        $sponsor_flag = 0;
        if(!empty($room_id)){
            $to_client_uid = $room_id;
            $room_user = Gateway::getClientInfoByGroup($room_id);
            foreach ($room_user as $key => $row) {
                if($row['openid']==$to_client_uid){
                    $sponsor_flag = 1;
                }
            }
        }
        return $sponsor_flag;
    }

    //获取银行金币
    public function get_bank_points(){
        $day_max_point = config('bank_max_points');//规则：一天，最多可以领取180个金币
        $max_point = 60;//>=3小时，单次获取最大金币数
        $points = 0;//
        $user_info_extend=db('user_info_extend')->where(['user_id'=>$this->user_info['id']])->find();
        $user_get_point =$user_info_extend['user_get_point'];//用户当天已经获得金币数
        $startdate=$user_info_extend['last_bank_point_time'];//'1520215200';//"2018-03-05 10:00:00";//上次领取记录的时间
        $enddate=time();//
        $flag = date('Y-m-d',$startdate)!=date('Y-m-d',$enddate)?true:false;

        if($user_get_point<$day_max_point || $flag){
            $day=floor(($enddate-$startdate)/86400);//相差天数
            $minute=floor(($enddate-$startdate)%86400/60);//相差分钟数
            //计算得出金币数
            $points =  (int)(($minute/$max_point)*2*10);
            if($day>0 || $points>$max_point){//超出最大时间和最大金币数
              $points = $max_point;
            }
            $curr_point = $user_get_point + $points;//当前金币数
            if(!$flag && $curr_point>$day_max_point){//超出当天总金币数,最多只能领剩余的
              $points = $day_max_point - $user_get_point;
            }
            Db::startTrans();
            try{
                if($points>0){//写金币日志
                    $time = time();
                    //数据库操作
                    if($flag){//跨天，直接更新当天开始
                      $data = [
                        'last_bank_point_time'=>$time,
                        'user_get_point'=>$points
                      ];
                    }else{//为当天，累加数量
                      $data = [
                        'last_bank_point_time'=>$time,
                        'user_get_point'=>['exp',"user_get_point+$points"]
                      ];
                    }
                    if($user_info_extend){
                        db('user_info_extend')->where(['user_id'=>$this->user_info['id']])->update($data);
                    }else{
                        $data['user_id']= $this->user_info['id'];
                        db('user_info_extend')->insertGetId($data);
                    }
                    $where=[
                        'user_id'     =>$this->user_info['id'],
                        'user_name'   =>$this->user_info['display_name'],
                        'points'      =>$points,
                        'remark'      =>'获取银行金币',
                        'stage'       =>'getBankPoints',
                        'create_time' =>$time
                    ];
                    db('points_log')->insertGetId($where);
                    $coin=[
                        'points'=>['exp',"points+$points"]
                    ];
                    db('user')->where(['id'=>$this->user_info['id']])->update($coin);//储存金币进用户表
                }
                Db::commit();
                return $this->json_success('ok',['points'=>$points,'time'=>$time]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json_error('未够时间领取！'); 
            }
        }else{
            return $this->json_error('今日金币已领完！');   
        }
    }
    
    //加好友
    public function is_friends(){
        $to_user_id = input('to_user_id');
        $room_id = input('room_id',0);//邀请人的房间id
        $data=[];
        if(!$to_user_id || $to_user_id==$this->user_info['id']){
            return $this->json_error('参数错误！');
        }
        $sponsor_flag = $this->check_sponsor($room_id);//检查房主是否离开房间
        $where=[
            'user_id'   => $this->user_info['id'],
            'to_user_id'=> $to_user_id
        ];
        $friends_info=db('friends')->where($where)->find();
        if(!$friends_info){
            $data[0]=[
                'user_id'       => $this->user_info['id'],
                'to_user_id'    => $to_user_id,
                'bind_type'     => 1,
                'create_time'   => time()
            ];
        }
        $map=[
            'user_id'   => $to_user_id,
            'to_user_id'=> $this->user_info['id']
        ];
        $friends_info2=db('friends')->where($map)->find();
        if(!$friends_info2){
             $data[1]=[
                'user_id'       => $to_user_id,
                'to_user_id'    => $this->user_info['id'],
                'bind_type'     => 1,
                'create_time'   => time()
            ];
        }
        if($data){
            foreach($data as $value){
                db('friends')->insertGetId($value);
            }
            return $this->json_success('ok',['status'=>1,'msg'=>'已成功添加好友','sponsor_flag'=>$sponsor_flag]);
        }else{
            return $this->json_success('ok',['status'=>0,'msg'=>'好友已存在','sponsor_flag'=>$sponsor_flag]);
        }
    }
    
    //是否有足够金币参加比赛
    public function is_enough_points(){
        $grad_id = input('grad_id');
        if(!$grad_id){
            return $this->json_error('参数错误！');
        }
        $grad_info=db('grad')->where('id',$grad_id)->find();
        if($this->user_info['points']>=$grad_info['consume_point']){
            return $this->json_success('ok',['msg'=>'金币足够，可以进行比赛']);
        }else{
            return $this->json_error('金币不足！');
        }
    }
    
    //设置
    public function is_setting($is_arr=false){
        //1为开启，2为关闭
        $is_sound=input('is_sound');
        $is_send=input('is_send');
        $user_info_extend=db('user_info_extend')->where(['user_id'=>$this->user_info['id']])->find();
        if($is_sound=="frist" || $is_send=="frist" || $is_arr){//第一次加载
            if(!$user_info_extend){
                $is_check=$is_send_check=false;
                $sound=$send=2;
            }else{
                $is_check=$user_info_extend['is_sound']?true:false;
                $sound=$user_info_extend['is_sound']?1:2;
                $is_send_check=$user_info_extend['is_send']?true:false;
                $send=$user_info_extend['is_send']?1:2;
            }
        }else{
            if($is_sound){
                $is_sound=$is_sound==2?1:2;//改变状态存值
                $data['is_sound']=$is_sound==2?0:1; 
                $is_check=$is_sound==2?false:true;
                $sound=$is_sound==2?2:1;
            }else{
                if($user_info_extend){
                    $is_check=$user_info_extend['is_sound']?true:false;
                    $sound=$user_info_extend['is_sound']?1:2;
                }else{
                    $is_check=false;
                    $sound=2;
                }
            }
            if($is_send){
                $is_send=$is_send==2?1:2;//改变状态存值
                $data['is_send']=$is_send==2?0:1; 
                $is_send_check=$is_send==2?false:true;
                $send=$is_send==2?2:1;
            }else{
                if($user_info_extend){
                    $is_send_check=$user_info_extend['is_send']?true:false;
                    $send=$user_info_extend['is_send']?1:2;
                }else{
                    $is_send_check=false;
                    $send=2;
                }
            }
            if($is_send || $is_sound){
                if($user_info_extend){
                    db('user_info_extend')->where(['user_id'=>$this->user_info['id']])->update($data);
                }else{
                    $data['user_id']= $this->user_info['id'];
                    db('user_info_extend')->insertGetId($data);
                }
            } 
        }
        $set=[
            'is_check'      =>$is_check,
            'is_send_check' =>$is_send_check,
            'sound'         =>$sound,
            'send'          =>$send
        ];
        if($is_arr)return $set;//
        return $this->json_success('ok',$set);  
    }
    
    //分享加金币
    public function share_points(){
        $share_type= input('share_type');
        $encryptedData= input('encryptedData');//加密数据
        $iv= input('iv');
        $is_group= input('is_group',0);//是否分享到群
        $group_id = '';//群id
        if($is_group && !empty($encryptedData) && !empty($iv)){
            $result = decrypt_wxapp_data($this->token_data['session_key'],$encryptedData,$iv);
            if(empty($result['openGId'])){//是否有群id
                return $this->json_error('解密参数错误！');
            }else{
                $group_id = $result['openGId'];
                $user_id = $this->user_info['id'];
                \think\Loader::model('UserModel')->user_join_group($user_id,$group_id);//分享加入群
            }
        }
        
        if(!$share_type){
            return $this->json_error('参数错误！');
        }
        $config_points=config($share_type);
        $todayTime=strtotime(date('Y-m-d'));
        $tomorrowTime= strtotime(date('Y-m-d',strtotime('+1 day')));
        $where['user_id']=$this->user_info['id'];
        $where['share_type']=$share_type;
        $where['create_time']=array(array('egt',$todayTime),array('elt',$tomorrowTime),'and');
        $count=Db::name('share_log')->where($where)->count();
        $count=$count+1;
        $points=0;
        if($config_points){
            if($count<=$config_points['num']){
                $points=$config_points['points'];
            }else{
                return $this->json_error('分享次数已达到上限！');
            }
        }
        if($points<=0){
            return $this->json_error('金币参数未设置！');
        }
        $share_data=[//分享日志
            'user_id'=> $this->user_info['id'],
            'user_name'=> $this->user_info['display_name'],
            'share_type'=>$share_type,
            'group_id'=>$group_id,
            'share_url'=>'',
            'create_time'=>time()
        ];
        $point_data=[//金币日志
            'user_id'=> $this->user_info['id'],
            'user_name'=> $this->user_info['display_name'],
            'points'=>$points,
            'remark'=>'分享获得金币',
            'stage'=>'share',
            'create_time'=> time()
        ];
        $user_data=[//user加金币
            'points'=>['exp',"points+$points"]
        ];
        Db::startTrans();
        try{
            db('share_log')->insertGetId($share_data);
            db('points_log')->insertGetId($point_data);
            db('user')->where('id', $this->user_info['id'])->update($user_data);
            Db::commit();
            return $this->json_success('ok',['points'=>$points,'msg'=>'分享成功！']);
        } catch (Exception $ex) {
            Db::rollback();
            return $this->json_error('分享失败！');
        }
    }
    
}
